package com.youlv.yl.manager.impl;

import com.youlv.yl.config.SystemConfig;
import com.youlv.yl.dao.OssLogDao;
import com.youlv.yl.entity.network.OssLog;
import com.youlv.yl.manager.intf.OssService;
import com.youlv.yl.util.*;
import com.youlv.yl.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author fenghe
 * @date 2022/1/12 19:57
 */
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OssLogDao dao;

    @Override
    public R upload(MultipartFile file) {
        String url = uploadOss(file);
        if(StringUtils.isNotEmpty(url)) {
            return R.ok(url);
        } else {
            return R.fail("上传异常，请检查");
        }
    }

    @Override
    public R updateMore(MultipartFile[] files) {
        if(files != null && files.length > 0) {
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files) {
                String url = uploadOss(file);
                if(StringUtils.isNotEmpty(url)) {
                    urls.add(url);
                }
            }
            return R.ok(urls);
        }
        return R.fail("请检查上传的内容");
    }

    /** 实现上传资源到oss中*/
    private String uploadOss(MultipartFile file) {
        // 1.验证
        if(file != null && !file.isEmpty()) {
            // 2.实现重命名
            String objName = FileUtils.rename(file.getOriginalFilename());
            Date date = DateUtils.getYearTime(SystemConfig.OSS_URL_TIME);
            try {
                //3.图片审核-基于百度的人工智能
                byte[] data = file.getBytes();
                BaiduContentUtils.imgCensor(data);
                //4.实现上传
                String url = AliOssUtils.upload(objName, file.getBytes(), date);
                if(StringUtils.isNotEmpty(url)) {
                    // 5.记录日志
                    dao.insert(new OssLog(AliOssUtils.bucket, "图片", objName, url, date));
                    // 返回url
                    return url;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
